home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part2 / 15214 < prev    next >
Encoding:
Text File  |  1996-08-05  |  1.7 KB  |  50 lines

  1. Path: morgan.cnu.edu!dlabell
  2. From: dlabell@pcs.cnu.edu (Daniel LaBell)
  3. Newsgroups: comp.lang.c++
  4. Subject: casting a void pointer back to a function pointer
  5. Date: 04 Apr 1996 07:10:45 GMT
  6. Organization: CNU
  7. Message-ID: <DLABELL.96Apr4021045@columbia.pcs.cnu.edu>
  8. NNTP-Posting-Host: columbia.pcs.cnu.edu
  9.  
  10. I'm going to skip explaining why I want to do this, and get right to the
  11. problem.  How do I cast a pointer to a function pointer?
  12.  
  13. Here is trivial example that shows the problem.
  14.  
  15. void foo1(){  cout << " foo1 " << endl; }
  16. void foo2(){  cout << " foo2 " << endl; }
  17. void foo3( int x )
  18. { cout << " foo3, argument = " << x << endl; }
  19.  
  20. void do_a_foo( void (*fun)() )
  21. {  (*fun)(); }
  22. void do_a_foo2( int x,  void (*fun) (int ) )
  23. {  (*fun) ( x ); } 
  24. int main()
  25. {
  26.   do_a_foo  ( foo1 );
  27.   do_a_foo  ( foo2 );
  28.   do_a_foo2 ( 2, foo3 );
  29.   void * x=foo2;
  30.   do_a_foo  (x); // I don't know the syntax to do this cast. :(
  31.   return 0;
  32. }
  33. I get this warning message from g++:
  34. :/home/student/dlabell/C/test.cc: In function `int main()':
  35. :/home/student/dlabell/C/test.cc:21: warning: ANSI C++ forbids implicit conversion from `void *' in argument passing
  36. :
  37. :Compilation finished at Thu Apr  4 01:18:20
  38.  
  39. So, now my program isn't portable, and if I overload do_a_foo instead of
  40. making do_a_foo2, it wouldn't compile at all.  So, I need to know the syntax
  41. for casting a pointer to a pointer to a function.  Can this be done in a
  42. portable way? ( how about for ANSI C? ) If not, can this be done in
  43. g++/gcc? And also if it isnt ANSI wouldn't that violate the premise that
  44. "any pointer can be cast to void * and back again without loss of
  45. information"?  Or can I declare a type of pointer to a function?
  46.  
  47.  
  48. --
  49. Daniel LaBell
  50.